package com.jiantong.work.impl.service;

import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.jiantong.common.util.UserUtil;
import com.jiantong.user.ext.LoginUser;
import com.jiantong.user.impl.dao.BreedFactoryDao;
import com.jiantong.work.enums.DocumentsDeleteFlag;
import com.jiantong.work.enums.ImmunizationRecordStatus;
import com.jiantong.work.impl.dao.ImmunizationRecordDao;
import com.jiantong.work.model.ImmunizationRecord;
import com.jiantong.work.service.ImmunizationRecordReadService;
import io.terminus.boot.rpc.common.annotation.RpcProvider;
import io.terminus.common.model.PageInfo;
import io.terminus.common.model.Paging;
import io.terminus.common.model.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by maowenjie on 2017/3/30.
 */
@Slf4j
@Service
@RpcProvider
public class ImmunizationRecordReadServiceImpl implements ImmunizationRecordReadService {
    private ImmunizationRecordDao immunizationRecordDao;
    private final BreedFactoryDao breedFactoryDao;

    @Autowired
    public ImmunizationRecordReadServiceImpl(ImmunizationRecordDao immunizationRecordDao, BreedFactoryDao breedFactoryDao) {
        this.immunizationRecordDao = immunizationRecordDao;
        this.breedFactoryDao = breedFactoryDao;
    }

    @Override
    public Response<ImmunizationRecord> findById(Long id) {
        try {
            ImmunizationRecord immunizationRecord = immunizationRecordDao.findById(id);
            if (immunizationRecord == null) {
                log.error("immunizationRecord(id={}) is not found", id);
                return Response.fail("immunizationRecord.not.found");
            }
            return Response.ok(immunizationRecord);
        } catch (Exception e) {
            log.error("failed to find breedReport(id={}), cause:{}", id, Throwables.getStackTraceAsString(e));
            return Response.fail("immunizationRecord.find.fail");
        }
    }

    @Override
    public Response<Map<String, Object>> findStatusById(Long id) {
        try{
            Integer status = immunizationRecordDao.findStatusById(id);
            Map<String , Object> map = Maps.newHashMap();
            if(status == null){
                log.error("immunization Record status (id={}) is not found", id);
                return Response.fail("immunization record.status.not.found");
            }
            map.put("status",status);
            return Response.ok(map);
        }catch (Exception e){
            log.error("immunizationRecord status (id={}) is not found", id);
            return Response.fail("immunization record.status.not.found");
        }
    }

    @Override
    public Response<Paging<ImmunizationRecord>> pagingImmunizationRecord(Integer pageNo, Integer pageSize, Integer status , Long breedFactoryId) {
        try {
            PageInfo pageInfo = new PageInfo(pageNo, pageSize);
            Map<String, Object> criteria = Maps.newHashMap();
            if (status !=null) criteria.put("status", status);

            criteria.put("breedFactoryId",breedFactoryId);

            criteria.put("deleteFlag", DocumentsDeleteFlag.NORMAL.value());
            return Response.ok(immunizationRecordDao.paging(pageInfo.getOffset(), pageInfo.getLimit(), criteria));
        } catch (Exception e) {
            log.error("failed to find immunizationRecord(id={}), cause:{}", status, Throwables.getStackTraceAsString(e));
            return Response.fail("immunizationRecord.find.fail");
        }
    }

    @Override
    public Response<Paging<ImmunizationRecord>> pagingImmunizationRecordGqv(Integer pageNo, Integer pageSize, Long breedFactoryId,Integer breedType, Date fromDate, Date toDate) {
        try {
            PageInfo pageInfo = new PageInfo(pageNo, pageSize);
            Map<String, Object> criteria = Maps.newHashMap();

            List<Long> breedFactoryIds = new ArrayList<>();
            if(breedFactoryId!=null){
                breedFactoryIds.add(breedFactoryId);
            }else {
                LoginUser loginUser = UserUtil.getCurrentUser();
                breedFactoryIds = loginUser.getBreedFactoryIds();
            }
            //在这里根据breedType赛选一下养殖场,从breedFactoryIds中去掉不是这个养殖类型的养殖场ID
            if (breedType != null) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("breedType",breedType);
                if(!breedFactoryIds.isEmpty()) {
                    map.put("breedFactoryIds", breedFactoryIds);
                    breedFactoryIds = breedFactoryDao.selectedByType(map);
                }
            }

            if(!breedFactoryIds.isEmpty()) criteria.put("breedFactoryIds", breedFactoryIds);
            else return Response.ok(new Paging<>(0L,new ArrayList<>()));

            if(fromDate != null) criteria.put("fromDate", fromDate);

            if(toDate != null) criteria.put("toDate",toDate);
            criteria.put("status",ImmunizationRecordStatus.FINISHED.value());
            criteria.put("deleteFlag", DocumentsDeleteFlag.NORMAL.value());
            return Response.ok(immunizationRecordDao.pagingImmunizationRecordGqv(pageInfo.getOffset(), pageInfo.getLimit(), criteria));
        } catch (Exception e) {
            log.error("failed to find ImmunizationDetection fromDate={},fromDate={},toDate={}),cause:{}", fromDate,toDate,Throwables.getStackTraceAsString(e));
            return Response.fail("ImmunizationDetection.find.fail");
        }
    }

    @Override
    public Response<Paging<ImmunizationRecord>> pagingImmunizationRecordGqv1(Integer pageNo, Integer pageSize, Map map) {
      try{
          PageInfo pageInfo = new PageInfo(pageNo, pageSize);
          return Response.ok(immunizationRecordDao.pagingImmunizationRecordGqv(pageInfo.getOffset(), pageInfo.getLimit(), map));
      }catch(Exception e){
          log.error("failed to find ImmunizationDetection fromDate={},fromDate={},toDate={}),cause:{}", map,Throwables.getStackTraceAsString(e));
          return Response.fail("ImmunizationDetection.find.fail");
      }


    }


    public List<Map<String,Object>> findAlltimesAlltype(Map map) {
        return immunizationRecordDao.findAlltimesAlltype(map);
    }
    /**
     * 溯源
     *
     * @param breedFactoryId 养殖场id
     * @param markNumber     耳标号（完整）
     * @return ImmunizationRecord
     */
    @Override
    public Response<ImmunizationRecord> findByEarNumber(Long breedFactoryId, String markNumber) {
        try{
            Map<String , Object> criteria = Maps.newHashMap();
            criteria.put("breedFactoryId",breedFactoryId);
            criteria.put("markNumber",markNumber);
            criteria.put("status",ImmunizationRecordStatus.FINISHED.value());
            criteria.put("deleteFlag",DocumentsDeleteFlag.NORMAL.value());
            return Response.ok(immunizationRecordDao.findByEarNumber(criteria));
        }catch (Exception e){
            log.error("failed to find ImmunizationRecord by ear number , case = {}",Throwables.getStackTraceAsString(e));
            return Response.fail("failed to find ImmunizationRecord by ear number");
        }

    }

    @Override
    public List<ImmunizationRecord> findByBreedId(Long breedID) {
        Map map =new HashMap();
        map.put("breedFactoryId",breedID);
        return immunizationRecordDao.list(map);
    }

    @Override
    public Response<List<Long>> findIdsForWeb(Map<String, Object> map) {
        try{
            return Response.ok(immunizationRecordDao.findIdsForWeb(map));
        }catch (Exception e){
            log.error("failed to find ids for web , case = {}",Throwables.getStackTraceAsString(e));
            return Response.fail("failed to find ids for web");
        }
    }
}
